<?php
    /**
     * Created by PhpStorm.
     * User: mybook-lhp
     * Date: 18/10/19
     * Time: 下午4:28
     */

    namespace app\store\api;


    use app\base\model\WalletProductModel;
    use app\common\controller\API;

    use app\face2market\model\Face2marketOrderLimitModel;
    use app\payment\logic\OmniPayAliPay;
    use app\payment\logic\OmniPayWechatPay;
    use app\payment\logic\PayBase;
    use app\payment\logic\PayProduct;
    use app\payment\logic\PayWallet;
    use app\payment\logic\PayWechatOriginal;
    use app\payment\model\PaymentOrderModel;
    use app\payment\model\WalletModel;
    use app\store\model\GoodsModel;
    use app\store\model\OrderModel;

    class Payment extends API
    {
        /**
         * 支付
         * api POST /store/payment/start
         *
         * @param int $pay_type 支付类型（alipay:支付宝wxpay微信wallet钱包product商品支付）
         * @param int $point 积分
         * @param int $order_sn 订单编号
         *
         * @return array|int|mixed|void
         * @throws \think\db\exception\DataNotFoundException
         * @throws \think\db\exception\ModelNotFoundException
         * @throws \think\exception\DbException
         */
        public function start()
        {

            $data = $this->request->param();
            $data['member_id'] = $this->member_id;
            $this->check_validate($data, 'order.start');
            unset($data['member_id']);

            list($pay_sn, $pay_money, $point) = $this->run_moeny($data);

            switch ($data['pay_type']) {
                case 'alipay'://支付宝支付

                    $this->result(OmniPayAliPay::send($pay_sn, $pay_money));
                    break;
                case 'wxpay'://微信支付
                    $this->result((new PayWechatOriginal)->send($pay_sn, $pay_money));

                    $this->result(OmniPayWechatPay::send($pay_sn, $pay_money));
                    break;
                case 'wallet'://钱包支付
                    return PayWallet::send(PayBase::PAY_TYPE_WALLET_PAY, $pay_sn, $pay_money, $point);
                    break;
                case 'point'://积分支付
                    return PayWallet::send(PayBase::PAY_TYPE_POINT, $pay_sn, $pay_money, $point);
                    break;
                case 'product'://商品支付
                    return PayProduct::send($pay_sn, $pay_money, $point);
                    break;
                default:
                    $this->error('不支持的支付类型！');
            }
        }

        protected function run_moeny($data)
        {


            $module_config = module_config('store');
            $module_config['pay_point_deduction_ratio'];
            $OrderModel = OrderModel::where(['order_sn' => $data['order_sn'], 'buyer_id' => $this->member_id])->find();
            
            if (!$OrderModel)
                $this->error('订单不存在！');
            $WalletModel = WalletModel::userwallet($this->member_id);

            $amount = (float)$OrderModel['amount'];

            if ($data['pay_type'] == 'point') {
                return [$OrderModel['pay_sn'], 0, (int)$data['point'] * 100];
            }

            //当前订单最多使用多少积分
            $max_point = $amount * $module_config['pay_point_deduction_ratio'] * 100;
            //当提交积分大于商品最大积分数则等于当前商品最大积分数；


            if ($data['point'] > 0) {
                $Offset_money = $data['point'] / $module_config['pay_point_deduction_ratio'];
            } else {
                $Offset_money = 0;
            }


            $point = $Offset_money >= $amount ? $max_point : $data['point'];

            $Offset_money = $Offset_money >= $amount ? $amount : $Offset_money;
            //积分兑换后的金额
            $pay_money = $amount - $Offset_money;

            if ($WalletModel['money'] < $pay_money) {
                $this->error('余额不足');
            }
            return [$OrderModel['pay_sn'], $pay_money * 100, (int)$point * 100];

        }

        /**
         * 获取支付方式
         * api POST /store/payment/check_pay_type
         *
         * @return array|int|mixed
         */
        public function check_pay_type()
        {

            $this->member_id;
            $WalletModel = WalletModel::where(['member_id' => $this->member_id])->column('member_id,money,money_status,point,point_status');
            $WalletModel = $WalletModel[$this->member_id];
            $WalletProductModel = WalletProductModel::where([
                'member_id' => $this->member_id,
                'product_id' => 1
            ])->column('member_id,product_num,status');
            $WalletProductModel = $WalletProductModel[$this->member_id];
            $hang_price_region = Face2marketOrderLimitModel::hang_price_region(module_config('face2market'));
            $module_config = module_config('store');
            $module_config['pay_type'] = isset($module_config['pay_type']) && $module_config['pay_type'] != "" ? $module_config['pay_type'] : [];

            $_pay_type = [
                'pays' => [
                    'wallet' => [
                        'name' => '钱包',
                        'is_pay' => ($WalletModel['money_status'] && in_array(OrderModel::PAY_VIEW_WALLET, $module_config['pay_type'])),
                        'number' => $WalletModel['money']
                    ],
                    'point' => [
                        'name' => '积分',
                        'is_pay' => ($WalletModel['point_status'] == WalletModel::STATUS_SUCCESS && ($module_config['store_price_view'] == GoodsModel::PRICE_VIEW_POINT || $module_config['store_price_view'] == GoodsModel::PRICE_VIEW_PRICE_POINT)) ? true : false,
                        'number' => $WalletModel['point'] / 100,
                        'point_ratio' => ($module_config['pay_point_deduction_ratio'] / 100),
                    ],
                    'product' => [
                        'name' => '树',
                        'is_pay' => ($WalletProductModel['status'] && in_array(OrderModel::PAY_VIEW_PRODUCT, $module_config['pay_type'])),
                        'number' => $WalletProductModel['product_num'],
                        'price' => $hang_price_region['sell_price'],
                    ],
                    'alipay' => ['name' => '支付宝', 'is_pay' => in_array(OrderModel::PAY_VIEW_ALIPAY, $module_config['pay_type'])],
                    'wxpay' => ['name' => '微信', 'is_pay' => in_array(OrderModel::PAY_VIEW_WECHATPAY, $module_config['pay_type'])],
                ],
            ];

            $this->result($_pay_type);
        }
    }